from docx import Document
from docx.shared import Pt, RGBColor, Inches, Cm
from docx.oxml.ns import qn
from docx.oxml import parse_xml
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.enum.text import WD_ALIGN_PARAGRAPH
import pandas as pd
import os


def process_docx_tables(file_path, output_path=None):
    """
    处理Word文档中的所有表格

    参数:
        file_path: 输入文档路径
        output_path: 输出文档路径（可选）
    """
    try:
        # 打开文档
        doc = Document(file_path)

        print(f"文档包含 {len(doc.tables)} 个表格")

        # 处理每个表格
        for table_index, table in enumerate(doc.tables):
            print(f"\n处理表格 {table_index + 1} ({len(table.rows)}行 x {len(table.columns)}列)")

            # 1. 读取表格数据
            table_data = read_table_data(table)
            if table_data:
                print(f"表格内容:")
                # 打印表格数据（最多显示5行）
                for i, row in enumerate(table_data[:5]):
                    print(f"行 {i + 1}: {row}")
                if len(table_data) > 5:
                    print(f"... 还有 {len(table_data) - 5} 行未显示")

            # 2. 分析表格结构
            analyze_table_structure(table)

            # 3. 修改表格样式（可选）
            try:
                style_table(table)
            except Exception as e:
                print(f"样式设置失败: {str(e)}")

            # 4. 添加新行（可选）
            if len(table.columns) >= 3:
                try:
                    add_table_row(table, ["新行", "添加的数据", "示例"])
                except Exception as e:
                    print(f"添加行失败: {str(e)}")

        # 5. 添加新表格（可选）
        try:
            add_new_table(doc, 3, 4, "新添加的表格")
        except Exception as e:
            print(f"添加新表格失败: {str(e)}")

        # 保存修改后的文档
        if output_path:
            # 确保输出目录存在
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            doc.save(output_path)
            print(f"\n文档已保存至: {output_path}")
        else:
            print("\n文档处理完成（未保存修改）")

    except Exception as e:
        print(f"处理文档时发生错误: {str(e)}")
        raise


def read_table_data(table):
    """读取表格数据到二维列表"""
    data = []
    for row in table.rows:
        row_data = []
        for cell in row.cells:
            # 获取单元格中的所有文本（包括段落）
            cell_text = "\n".join([para.text for para in cell.paragraphs])
            row_data.append(cell_text.strip())
        data.append(row_data)
    return data


def analyze_table_structure(table):
    """分析表格结构"""
    # 检查是否有合并单元格
    has_merged_cells = False
    try:
        for row in table.rows:
            for cell in row.cells:
                # 检查单元格是否被合并（通过列跨度和行跨度判断）
                tc = cell._tc
                if (tc.gridSpan is not None and tc.gridSpan.val > 1) or \
                        (tc.vMerge is not None and tc.vMerge.val != 'restart'):
                    has_merged_cells = True
                    break
            if has_merged_cells:
                break
    except:
        has_merged_cells = "未知"

    print(f"表格包含合并单元格: {has_merged_cells}")

    # 检查表格标题
    if len(table.rows) > 0:
        try:
            first_row = table.rows[0]
            header_cells = [cell.text.strip() for cell in first_row.cells]
            print(f"表头内容: {header_cells}")
        except:
            print("读取表头失败")


def style_table(table):
    """设置表格样式 - 使用安全方法"""
    try:
        # 尝试设置表格样式（使用更通用的样式）
        table.style = "Table Grid"  # 有些模板中有这个样式
    except:
        try:
            table.style = "Light Shading"  # 另一个常见样式
        except:
            print("无法应用预定义表格样式，使用手动样式设置")
            # 手动设置基本样式
            table.autofit = False
            table.allow_autofit = False
            table.alignment = WD_TABLE_ALIGNMENT.CENTER

    # 设置表头样式
    if len(table.rows) > 0:
        try:
            header_row = table.rows[0]
            for cell in header_row.cells:
                # 设置背景色
                try:
                    shading_elm = parse_xml(f'<w:shd {qn("w:fill")}="D9E1F2"/>')
                    tcPr = cell._tc.get_or_add_tcPr()
                    tcPr.append(shading_elm)
                except:
                    pass

                # 设置文字样式
                for paragraph in cell.paragraphs:
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    for run in paragraph.runs:
                        run.font.bold = True
                        run.font.size = Pt(12)
                        run.font.color.rgb = RGBColor(0, 0, 0)  # 黑色
        except Exception as e:
            print(f"设置表头样式失败: {str(e)}")


def add_table_row(table, row_data):
    """向表格添加新行"""
    new_row = table.add_row()
    for i, cell in enumerate(new_row.cells):
        if i < len(row_data):
            # 清空单元格内容并添加新文本
            cell.text = ""
            p = cell.paragraphs[0]
            p.add_run(str(row_data[i]))
            # 设置垂直居中
            try:
                cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
            except:
                pass


def add_new_table(doc, rows, cols, title=None):
    """在文档末尾添加新表格 - 使用安全方法"""
    # 添加标题
    if title:
        try:
            doc.add_paragraph(title, style="Heading 2")
        except:
            p = doc.add_paragraph(title)
            p.runs[0].font.bold = True
            p.runs[0].font.size = Pt(14)

    # 创建表格
    table = doc.add_table(rows=rows, cols=cols)

    # 尝试设置表格样式
    try:
        table.style = "Table Grid"
    except:
        try:
            table.style = "Light Shading"
        except:
            # 手动添加边框
            set_table_borders(table)

    # 填充表格数据
    for i in range(rows):
        for j in range(cols):
            cell = table.cell(i, j)
            cell.text = f"行 {i + 1} 列 {j + 1}"

    # 合并首行作为表头（如果可能）
    if rows > 0 and cols > 1:
        try:
            first_row = table.rows[0]
            first_cell = first_row.cells[0]
            last_cell = first_row.cells[cols - 1]
            first_cell.merge(last_cell)
            first_cell.text = "表头"
            first_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        except Exception as e:
            print(f"合并表头失败: {str(e)}")

    print(f"\n已添加新表格: {rows}行 x {cols}列")


def set_table_borders(table):
    """手动设置表格边框"""
    # 设置表格边框为实线
    tbl = table._tbl
    tblPr = tbl.tblPr

    # 添加边框属性
    tblBorders = parse_xml(
        '<w:tblBorders xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
        '<w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
        '<w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
        '<w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
        '<w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
        '<w:insideH w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
        '<w:insideV w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
        '</w:tblBorders>'
    )

    # 确保tblPr存在
    if tblPr is None:
        tblPr = parse_xml('<w:tblPr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>')
        tbl.insert(0, tblPr)

    # 添加边框
    tblPr.append(tblBorders)


def find_tables_in_document(file_path):
    """查找文档中的所有表格并返回基本信息"""
    try:
        doc = Document(file_path)
        tables_info = []

        for table_index, table in enumerate(doc.tables):
            info = {
                "index": table_index,
                "rows": len(table.rows),
                "columns": len(table.columns),
                "position": f"文档位置 {table_index + 1}/{len(doc.tables)}",
                "has_merged_cells": False,
                "header": []
            }

            # 检查合并单元格
            try:
                for row in table.rows:
                    for cell in row.cells:
                        tc = cell._tc
                        if (tc.gridSpan is not None and tc.gridSpan.val > 1) or \
                                (tc.vMerge is not None and tc.vMerge.val != 'restart'):
                            info["has_merged_cells"] = True
                            break
                    if info["has_merged_cells"]:
                        break
            except:
                info["has_merged_cells"] = "未知"

            # 获取表头
            if len(table.rows) > 0:
                try:
                    first_row = table.rows[0]
                    info["header"] = [cell.text.strip() for cell in first_row.cells]
                except:
                    pass

            tables_info.append(info)

        return tables_info

    except Exception as e:
        print(f"查找表格时出错: {str(e)}")
        return []


def extract_table_to_csv(file_path, table_index, output_csv):
    """将指定表格导出为CSV文件"""
    try:
        doc = Document(file_path)
        if table_index < 0 or table_index >= len(doc.tables):
            print(f"表格索引 {table_index} 超出范围")
            return False

        table = doc.tables[table_index]
        data = read_table_data(table)

        # 写入CSV
        import csv
        with open(output_csv, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerows(data)

        print(f"表格 {table_index} 已导出到 {output_csv}")
        return True

    except Exception as e:
        print(f"导出表格失败: {str(e)}")
        return False


if __name__ == "__main__":
    input_file = "D:\\hbyt\\AI智能投标\\2025_04_23_Word\\2025_04_23_Word\\Word\\1.0\\中文\\HR选育留用相关\\激励及绩效管理_v1.0_2201.docx"
    output_file = "D:\\hbyt\\AI智能投标\\1.docx"

    # # 处理表格
    # process_docx_tables(input_file, output_file)
    #
    # # 查找所有表格
    # print("\n文档中的所有表格:")
    # tables_info = find_tables_in_document(input_file)
    # print(tables_info)
    # for i, table_info in enumerate(tables_info):
    #     print(f"\n表格 {i}:")
    #     print(f"  行数: {table_info['rows']}, 列数: {table_info['columns']}")
    #     print(f"  位置: {table_info['position']}")
    #     print(f"  有合并单元格: {table_info['has_merged_cells']}")
    #     if table_info['header']:
    #         print(f"  表头: {table_info['header']}")

    # 导出第一个表格到CSV
    # if tables_info:
    extract_table_to_csv(input_file, 0, "D:\\hbyt\\AI智能投标\\table_csv\\table_0.csv")